package com.hspedu.tankgame06;

import javax.sound.sampled.*;
import java.applet.AudioClip;
import java.io.File;
import java.io.IOException;

//播放音乐
public class Music extends Thread{
    private String filename;

    public Music(String wavfile) {
        filename = wavfile;
    }

    @Override
    public void run() {
        File soundFile = new File(filename);


        AudioInputStream audioInputStream = null;
        try {
            audioInputStream = AudioSystem.getAudioInputStream(soundFile);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        AudioFormat format = audioInputStream.getFormat();
        SourceDataLine auline = null;
        DataLine.Info info = new DataLine.Info(SourceDataLine.class,format);

        try {
            auline = (SourceDataLine)AudioSystem.getLine(info);
            auline.open(format);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        auline.start();
        int nBytesRead = 0;
        //缓冲
        byte[] abData = new byte[512];

        try {
            nBytesRead = audioInputStream.read(abData,0,abData.length);
        } catch (IOException e) {
            e.printStackTrace();
            return;
        } finally {
            //System.out.println("音乐播放");
            auline.drain();
            auline.close();
        }
    }
}
